package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.CustomException;
import com.example.reggie.common.R;
import com.example.reggie.entity.Category;
import com.example.reggie.entity.Dish;
import com.example.reggie.entity.Setmeal;
import com.example.reggie.service.impl.CategoryServiceImpl;
import com.example.reggie.service.impl.DishServiceImpl;
import com.example.reggie.service.impl.SetmealServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*分类管理*/
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryServiceImpl categoryService;

    @Autowired
    SetmealServiceImpl service;

    @Autowired
    DishServiceImpl dishService;

    /*分页查询*/
    @GetMapping("/page")
    public R<IPage<Category>> page(Integer page,Integer pageSize){
        IPage<Category> iPage = categoryService.page(new Page<>(page, pageSize));

        return R.success(iPage);
    }

    /*新增分类*/
    @PostMapping
    public R<String> add(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }
    /*删除*/
    @DeleteMapping
    public R<String> deleteD(Long id){

        /*套餐*/
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        List<Setmeal> list = service.list(setmealLambdaQueryWrapper);
        if (list.size()!=0 ){
            /*return R.error("当前分类下有菜品，不能删除");*/
            throw new CustomException("当前分类下有套餐，不能删除");
        }

            /*菜品*/
            LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        List<Dish> list1 = dishService.list(dishLambdaQueryWrapper);
        if (list1.size()!=0){
//                return R.error("当前分类下有菜品，不能删除");
            throw new CustomException("当前分类下有菜品，不能删除");
        }



        categoryService.removeById(id);
        return R.success("删除成功");

    }
    /*修改*/
    @PutMapping
    public R update(@RequestBody Category category){

        categoryService.updateById(category);
        return R.success("修改成功");

    }

    @GetMapping("/list")
    public R list(Integer type){
        LambdaQueryWrapper<Category> w = new LambdaQueryWrapper<>();
        w.eq(type!=null,Category::getType,type);
        List<Category> list = categoryService.list(w);
        return R.success(list);
    }
}
